//
//  HJGroupSettingController.m
//  KaiChat
//
//  Created by lx on 2023/11/6.
//

#import "HJGroupSettingController.h"
#import "HJGroupIntroductionCell.h"
#import "HJGroupMemberContentCell.h"
#import "HJGroupNoticeCell.h"
#import "HJSwitchCell.h"
#import "HJTitleCell.h"
#import "HJCenterTitleCell.h"
#import "HJGroupMemberModel.h"
#import "HJEditGroupInfoController.h"
#import "HJGroupEditNoticeController.h"
#import "HJGroupMemberController.h"
#import "HJSelectFridendsController.h"
#import "HJNavigationController.h"
#import "HJSelectGroupMemberController.h"
#import "HJIM.h"
#import "HJGroupRemoveManagerController.h"
#import "HJGroupTransferController.h"
#import "HJUIAlertController.h"
#import "HJChatSessionModel.h"
#import "HJGroupManagerController.h"
#import "HJAlertController.h"
#import "HJGroupNoticeController.h"
#import "HJAdministratorIntroduceController.h"
#import "HJUserInfoController.h"
#import "HJChatMessageModel.h"
#import "HJChatController.h"
#import "HJShareController.h"
#import "HJNavigationController.h"

@interface HJGroupSettingController ()<HJGroupMemberContentCellDelegate>

@property (nonatomic, strong) NSMutableArray <NSArray <HJCellModel *> * >*datas;
@property (nonatomic, strong) NSMutableDictionary *modelDict;
@property (nonatomic, strong) NSArray *allUserList;

@end


@implementation HJGroupSettingController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.title = @"Group Information";
    
    [self.tableView registerClass:HJGroupIntroductionCell.class forCellReuseIdentifier:@"HJGroupIntroductionCell"];
    [self.tableView registerClass:HJGroupMemberContentCell.class forCellReuseIdentifier:@"HJGroupMemberContentCell"];
    [self.tableView registerClass:HJGroupNoticeCell.class forCellReuseIdentifier:@"HJGroupNoticeCell"];
    [self.tableView registerClass:HJSwitchCell.class forCellReuseIdentifier:@"HJSwitchCell"];
    [self.tableView registerClass:HJTitleCell.class forCellReuseIdentifier:@"HJTitleCell"];
    [self.tableView registerClass:HJCenterTitleCell.class forCellReuseIdentifier:@"HJCenterTitleCell"];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    self.tableView.separatorInset = UIEdgeInsetsMake(0, leftRightMargin, 0, leftRightMargin);
    self.tableView.backgroundColor = UIColor.tj_F6F6F6Color;
    self.view.backgroundColor = UIColor.tj_F6F6F6Color;
    self.navigationBar.lineView.hidden = YES;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.bottom.offset(0);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRefreshGroupInfoNotification:) name:refreshGroupInfoNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSystemHandleCompleteNotification:) name:systemHandleCompleteNotification object:nil];
    
    self.navigationBar.rightBarButton = [HJBarButton barButtonWithImage:[UIImage imageNamed:@"share_icon"] target:self action:@selector(shareGroupButton)];
   
    if (self.groupModel.groupStatus == 1 || self.groupModel.status.intValue == 2) {
        [self showDisbandAlert];
    } else if (self.groupModel.userStatus == 2) {
        [self showKickedAlert];
    }
    
    [self queryGroupMemberDataComplete:^{
        NSLog(@"groupModel = %@", self.groupModel);
        [self buildData];
        [self.tableView reloadData];
    }];
    
    if (self.groupModel.role.intValue == 1 || self.groupModel.role.intValue == 2) {
        [self loadGroupMemberData];
    }
}


- (void)showKickedAlert {
    [HJGroupMemberModel bg_deleteAsync:[HJGroupMemberModel bg_tableNameWithGroupId:self.groupModel.groupId] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"), bg_sqlValue(HJUserInfo.userId)] complete:^(BOOL isSuccess) {}];
    dispatch_async_main_queue(^{
        [HJAlertController alertInController:self title:nil message:@"You have been removed from the group chat, and the chat messages will be cleared" left:nil right:^(HJAlertAction * _Nonnull action) {
            action.title = @"OK";
            action.titleColor = UIColor.tj_mainColor;
            [action setHandler:^{
                [HJIM.shareIM.conversationManager deleteConversationWithSessionId:self.groupModel.groupId completion:^(NSError * _Nonnull error) {
                    dispatch_async_main_queue(^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:deleteConversationNotification object:self.groupModel.groupId];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    });
                }];
            }];
        }];
    });
}

- (void)showDisbandAlert {
    [HJGroupMemberModel bg_deleteAsync:[HJGroupMemberModel bg_tableNameWithGroupId:self.groupModel.groupId] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"), bg_sqlValue(HJUserInfo.userId)] complete:^(BOOL isSuccess) {}];
    dispatch_async_main_queue(^{
        [HJAlertController alertInController:self title:nil message:@"This group has been disbanded, and relevant historical information will be cleared" left:nil right:^(HJAlertAction * _Nonnull action) {
            action.title = @"OK";
            action.titleColor = UIColor.tj_mainColor;
            [action setHandler:^{
                [HJIM.shareIM.conversationManager deleteConversationWithSessionId:self.groupModel.groupId completion:^(NSError * _Nonnull error) {
                    dispatch_async_main_queue(^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:deleteConversationNotification object:self.groupModel.groupId];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    });
                }];
            }];
        }];
    });
}


- (void)shareGroupButton {
    HJShareController *shareController = [[HJShareController alloc] init];
    shareController.objects = @[[NSString stringWithFormat:@"%@?userId=%@&groupId=%@&type=joinGroup", getGroupShareUrl(), HJUserInfo.userId, self.groupModel.groupId]];
    [HJTools.currentViewController presentViewController:shareController animated:YES completion:nil];
}

- (void)handleSystemHandleCompleteNotification:(NSNotification *)not {
    
    HJChatMessageModel *messageModel = not.object;
    if (![messageModel.groupId isEqualToString:self.groupModel.groupId]) return;

    if (messageModel.systemMsgType == HJChatSystemMsgTypeAddGroupManager ||
        messageModel.systemMsgType == HJChatSystemMsgTypeRemoveGroupManager) {
        [self loadGroupMemberData];
    }
    
    
    if (messageModel.systemMsgType == HJChatSystemMsgTypeJoinGroup ||
        messageModel.systemMsgType == HJChatSystemMsgTypeLeaveGroup ||
        messageModel.systemMsgType == HJChatSystemMsgTypeTransferGroup
        ) {
        [self loadGroupMemberData];
        return;
    }

    if (messageModel.systemMsgType == HJChatSystemMsgTypePostGroupNotice) {
        HJChatGroupModel *groupModel = [HJIM.shareIM.groupManager queryGroupInfoByGroupId:messageModel.sessionId];
        self.groupModel.notice = groupModel.notice;
        dispatch_async_main_queue(^{
            [self buildModelWithKey:@"notice"];
            [self reloadCellWithKey:@"notice"];
        });
    }
    
}
 
- (void)handleRefreshGroupInfoNotification:(NSNotification *)not {
    HJChatGroupModel *groupModel = not.object;
    
    if (self.modelDict.count == 0) return;

    
    self.groupModel.name = groupModel.name;
    self.groupModel.avatar = groupModel.avatar;
    self.groupModel.intro = groupModel.intro;
    
    [self buildModelWithKey:@"introduction"];
    [self reloadCellWithKey:@"introduction"];//修改简介没有通知
    
    [self buildModelWithKey:@"notice"];
    [self reloadCellWithKey:@"notice"];
    
    NSLog(@"self.groupModel = %@", self.groupModel);

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.datas[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCellModel *model = self.datas[indexPath.section][indexPath.row];
    model.indexPath = indexPath;
    if ([model.identifier isEqualToString:@"introduction"]) {
        HJGroupIntroductionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJGroupIntroductionCell" forIndexPath:indexPath];
        TJWeakify(self)
        [cell setDidClickEditButtonBlock:^{
            
            HJEditGroupInfoController *editGroupInfoController = [[HJEditGroupInfoController alloc] init];
            editGroupInfoController.groupModel = weakself.groupModel;
            [weakself.navigationController pushViewController:editGroupInfoController];
            
        }];
        cell.model = model;
        return cell;
    }
    
    if ([model.identifier isEqualToString:@"administrators"] || [model.identifier isEqualToString:@"members"]) {
        HJGroupMemberContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJGroupMemberContentCell" forIndexPath:indexPath];
        cell.delegate = self;
        cell.model = model;
        return cell;
    }
    
    if ([model.identifier isEqualToString:@"notice"]) {
        HJGroupNoticeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJGroupNoticeCell" forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }
     
    if ([model.identifier isEqualToString:@"founder"] ||
        [model.identifier isEqualToString:@"disband"] ||
        [model.identifier isEqualToString:@"leave"] ||
        [model.identifier isEqualToString:@"join"] ||
        [model.identifier isEqualToString:@"sendMessage"] ||
        [model.identifier isEqualToString:@"pending"]
        ) {
        HJCenterTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJCenterTitleCell" forIndexPath:indexPath];
        cell.model = model;
        cell.selectionStyle = [model.identifier isEqualToString:@"pending"] ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleDefault;
        return cell;
    }
    
    if ([model.identifier isEqualToString:@"mute"] || [model.identifier isEqualToString:@"top"]) {
        HJSwitchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJSwitchCell" forIndexPath:indexPath];
        cell.model = model;
        TJWeakify(self)
        
        [cell setSwitchValueChange:^(UISwitch * _Nonnull switchView) {
            
            if ([model.identifier isEqualToString:@"mute"]) {
                
                [HJHUD showGraceTimeLoadingInView:weakself.view];
                [HJIM.shareIM.conversationManager muteWithSessionId:weakself.groupModel.groupId isMute:!switchView.isOn type:HJChatTypeGroup complete:^(NSError * _Nonnull error) {
                    if (error) {
                        return;
                    }
                    
                    model.isOn = !switchView.isOn;
                    [switchView setOn:!switchView.isOn animated:YES];
                    weakself.groupModel.isMute = @(switchView.isOn);
                    [weakself.groupModel bg_saveOrUpdateAsync:nil];
                    HJChatSessionModel *sessionModel = [HJIM.shareIM.conversationManager getConversationBySessionId:weakself.groupModel.groupId];
                    sessionModel.isMute = toString(@(switchView.isOn));
                    [sessionModel bg_saveOrUpdateAsync:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationInfoNotification object:sessionModel];
                }];
                
            } else {
                [HJHUD showGraceTimeLoadingInView:weakself.view];
                [HJIM.shareIM.conversationManager topWithSessionId:weakself.groupModel.groupId isTop:!switchView.isOn type:HJChatTypeGroup complete:^(NSError * _Nonnull error) {
                    if (error) {
                        return;
                    }
                    model.isOn = !switchView.isOn;
                    [switchView setOn:!switchView.isOn animated:YES];
                    weakself.groupModel.isTop = @(switchView.isOn);
                    [weakself.groupModel bg_saveOrUpdateAsync:nil];
                    HJChatSessionModel *sessionModel = [HJIM.shareIM.conversationManager getConversationBySessionId:weakself.groupModel.groupId];
                    sessionModel.isTop = toString(@(switchView.isOn));
                    if (switchView.isOn) {
                        sessionModel.topTimestamp = [NSString stringWithFormat:@"%.f", [NSDate date].timeIntervalSince1970 * 1000];
                    } else {
                        sessionModel.topTimestamp = @"";
                    }
                    [sessionModel bg_saveOrUpdateAsync:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationInfoNotification object:sessionModel];
                }];
            }
        }];
        return cell;
    }
    
    HJTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJTitleCell" forIndexPath:indexPath];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HJCellModel *model = self.datas[indexPath.section][indexPath.row];
    if ([model.identifier isEqualToString:@"notice"]) {
        
        if (isEmptyString(self.groupModel.notice)) {
            if (self.groupModel.role.intValue == 1 || self.groupModel.role.intValue == 2) {
                HJGroupEditNoticeController *groupNoticeController = [[HJGroupEditNoticeController alloc] init];
                groupNoticeController.groupModel = self.groupModel;
                [self.navigationController pushViewController:groupNoticeController];
            } else {
                [HJAlertController alertInController:self title:nil message:@"Only group owner and admin can edit" left:nil right:^(HJAlertAction * _Nonnull action) {
                    action.title = @"OK";
                    action.titleColor = UIColor.tj_mainColor;
                }];
            }
        } else {
            HJGroupNoticeController *groupNoticeController = [[HJGroupNoticeController alloc] init];
            groupNoticeController.groupModel = self.groupModel;
            [self.navigationController pushViewController:groupNoticeController];
        }
        return;
    }
    
    if ([model.identifier isEqualToString:@"founder"]) {
        HJGroupTransferController *groupTransferController = [[HJGroupTransferController alloc] init];
        groupTransferController.groupId = self.groupModel.groupId;
        [groupTransferController setComplete:^{
            [self loadGroupMemberData];
        }];
        [groupTransferController showInController:self];
        return;
    }
    
    if ([model.identifier isEqualToString:@"disband"]) {
        HJUIAlertController *alert = [HJUIAlertController alertControllerWithTitle:nil message:@"Are you sure you want to disband this group?" preferredStyle:HJUIAlertControllerStyleActionSheet];
        [alert addAction:[HJUIAlertAction actionWithTitle:@"OK" style:HJUIAlertActionStyleDestructive handler:^(HJUIAlertAction * _Nonnull action) {
            [HJHUD showLoadingInView:self.view];
            [HJIM.shareIM.groupManager disbandGroupByGroupId:self.groupModel.groupId completion:^(NSError * _Nullable error) {
                [[NSNotificationCenter defaultCenter] postNotificationName:deleteConversationNotification object:self.groupModel.groupId];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }];
        }]];
        [alert addAction:[HJUIAlertAction actionWithTitle:@"Cancel" style:HJUIAlertActionStyleCancel handler:^(HJUIAlertAction * _Nonnull action) {
            
        }]];
        [alert showInViewController:self];
        return;
    }
    
    
    if ([model.identifier isEqualToString:@"leave"]) {
        HJUIAlertController *alert = [HJUIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"You will quit %@", self.groupModel.name] preferredStyle:HJUIAlertControllerStyleActionSheet];
        [alert addAction:[HJUIAlertAction actionWithTitle:@"OK" style:HJUIAlertActionStyleDestructive handler:^(HJUIAlertAction * _Nonnull action) {
            [HJHUD showLoadingInView:self.view];
            [HJIM.shareIM.groupManager exitGroupByGroupId:self.groupModel.groupId completion:^(NSError * _Nullable error) {
                [[NSNotificationCenter defaultCenter] postNotificationName:deleteConversationNotification object:self.groupModel.groupId];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }];
        }]];
        [alert addAction:[HJUIAlertAction actionWithTitle:@"Cancel" style:HJUIAlertActionStyleCancel handler:^(HJUIAlertAction * _Nonnull action) {
            
        }]];
        [alert showInViewController:self];
        return;
    }
    
    if ([model.identifier isEqualToString:@"groupManager"]) {
        HJGroupManagerController *groupManagerController = [[HJGroupManagerController alloc] init];
        groupManagerController.groupModel = self.groupModel;
        [self.navigationController pushViewController:groupManagerController];
    }
    
    if ([model.identifier isEqualToString:@"join"]) {
        [HJHUD showLoadingInView:self.view];
        [HJIM.shareIM.groupManager joinGroupInfoByGroupId:self.groupModel.groupId completion:^(NSError * _Nullable error) {
            if (error) {
                [HJHUD hiddenLoadingInView:self.view];
                if (([error.domain isEqualToString:ERRPRDOMAIN] && (error.code == groupNotExistCode || error.code == groupDisbandCode))) {
                    [HJHUD hiddenMessage];
                    [HJAlertController alertInController:getMainController() title:nil message:@"Group does not exist" left:nil right:^(HJAlertAction * _Nonnull action) {
                        action.title = @"OK";
                        action.titleColor = UIColor.tj_mainColor;
                        [action setHandler:^{
                            [self.navigationController popToRootViewControllerAnimated:YES];
                        }];
                    }];
                    return;
                }
                [HJHUD showMessage:error.localizedFailureReason];
                return;
            }
            
            [HJIM.shareIM.groupManager loadPublicGroupInfoByGroupId:self.groupModel.groupId completion:^(HJChatGroupModel * _Nullable groupModel, NSError * _Nullable infoError) {
                
                [HJHUD hiddenLoadingInView:self.view];

                self.groupModel.userStatus = groupModel.userStatus;
                self.groupModel.role = groupModel.role;

                if (groupModel.userStatus == 1) {
                    [self loadGroupMemberData];
                } else if (groupModel.userStatus == 3) {
                    [HJAlertController alertInController:self title:nil message:@"Application successful, awaiting review" left:nil right:^(HJAlertAction * _Nonnull action) {
                        action.title = @"OK";
                        action.titleColor = UIColor.tj_mainColor;
                    }];
                    [self buildData];
                    [self.tableView reloadData];
                }
            }];
        }];
        return;
    }
    
    if ([model.identifier isEqualToString:@"sendMessage"]) {
        
        HJChatSessionModel *sessionModel = [HJChatSessionModel sessionModelWithSessionId:toString(self.groupModel.groupId) sessionUserd:nil chatType:HJChatTypeGroup sessionName:self.groupModel.name];
        HJChatController *chatController = [HJChatController chatControllerWithSessionModel:sessionModel];
        [self.navigationController pushViewController:chatController];
        self.navigationController.viewControllers = [chatController removeNavChildViewControllers:@[@"HJGroupSettingController"]];
        return;
    }
    
    if ([model.identifier isEqualToString:@"pending"]) {
        return;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) return CGFLOAT_MIN;
    return 10;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColor.clearColor;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCellModel *model = self.datas[indexPath.section][indexPath.row];
    if (model.height > 0) return model.height;
    return 60;
}

- (void)groupMemberContentCell:(HJGroupMemberContentCell *)cell didClickItem:(HJGroupMemberModel *)memberModel {
    
    HJCellModel *cellModel = cell.model;
    
    if ([cellModel.identifier isEqualToString:@"members"]) {
        
        if ([memberModel.userId isEqualToString:@"add"]) {
            
            NSMutableArray *userIds = [NSMutableArray array];
            for (HJGroupMemberModel *obj in self.allUserList ) {
                [userIds addObject:obj.userId];
            }
            
            HJSelectFridendsController *selectFridendsController = [[HJSelectFridendsController alloc] init];
            selectFridendsController.memberUserIds = userIds;
            selectFridendsController.groupId = self.groupModel.groupId;
            [selectFridendsController setComplete:^{
                
                if (self.groupModel.openVerify.intValue == 1) {
                    [self loadGroupMemberData];
                    return;
                }
                
                [self queryGroupMemberDataComplete:^{
                    [self buildModelWithKey:@"members"];
                    [self reloadCellWithKey:@"members"];
                }];
            }];
            [selectFridendsController showInController:self];
            return;
        }
        
        if ([memberModel.userId isEqualToString:@"remove"]) {
            HJSelectGroupMemberController *selectGroupMemberController = [[HJSelectGroupMemberController alloc] init];
            selectGroupMemberController.type = HJSelectGroupMemberTypeRemoveMember;
            selectGroupMemberController.groupId = self.groupModel.groupId;
            selectGroupMemberController.role = self.groupModel.role;
            [selectGroupMemberController showInController:self];
            [selectGroupMemberController setComplete:^{
                [self queryGroupMemberDataComplete:^{
                    
                    [self buildModelWithKey:@"members"];
                    [self reloadCellWithKey:@"members"];
                    [self buildModelWithKey:@"administrators"];
                    [self reloadCellWithKey:@"administrators"];
                }];
            }];
            return;
        }
        
        if (self.groupModel.role.intValue == 0) return;
        
        HJUserInfoController *userInfoController = [[HJUserInfoController alloc] init];
        userInfoController.userId = memberModel.userId;
        [self.navigationController pushViewController:userInfoController];
        
    } else {
        if ([memberModel.userId isEqualToString:@"add"]) {
            HJSelectGroupMemberController *selectGroupMemberController = [[HJSelectGroupMemberController alloc] init];
            selectGroupMemberController.type = HJSelectGroupMemberTypeAddManager;
            selectGroupMemberController.groupId = self.groupModel.groupId;
            selectGroupMemberController.role = self.groupModel.role;
            [selectGroupMemberController showInController:self];
            [selectGroupMemberController setComplete:^{
                [self queryGroupMemberDataComplete:^{
                    [self buildModelWithKey:@"members"];
                    [self reloadCellWithKey:@"members"];
                    [self buildModelWithKey:@"administrators"];
                    [self reloadCellWithKey:@"administrators"];
                }];
            }];
            return;
        }
        
        if ([memberModel.userId isEqualToString:@"remove"]) {
            HJGroupRemoveManagerController *removeManagerController = [[HJGroupRemoveManagerController alloc] init];
            removeManagerController.groupId = self.groupModel.groupId;
            [removeManagerController showInController:self];
            [removeManagerController setComplete:^{
                [self queryGroupMemberDataComplete:^{
                    [self buildModelWithKey:@"members"];
                    [self reloadCellWithKey:@"members"];
                    [self buildModelWithKey:@"administrators"];
                    [self reloadCellWithKey:@"administrators"];
                }];
            }];
            return;
        }
        
        HJUserInfoController *userInfoController = [[HJUserInfoController alloc] init];
        userInfoController.userId = memberModel.userId;
        [self.navigationController pushViewController:userInfoController];
    }
    
}

- (void)groupMemberContentCellDidClickViewMoreButton:(HJGroupMemberContentCell *)cell {
    if ([cell.model.identifier isEqualToString:@"members"]) {
        HJGroupMemberController *groupMemberController = [[HJGroupMemberController alloc] init];
        groupMemberController.groupModel = self.groupModel;
        [self.navigationController pushViewController:groupMemberController];
    }
}

- (void)groupMemberContentCellDidClickInfoButton:(HJGroupMemberContentCell *)cell {
    HJAdministratorIntroduceController *administratorIntroduceController = [[HJAdministratorIntroduceController alloc] init];
    [administratorIntroduceController showInController:self];
}

- (void)loadGroupMemberData {
    [HJIM.shareIM.groupManager loadGroupMemberListWithGroupId:self.groupModel.groupId completion:^(NSArray<HJGroupMemberModel *> * _Nullable datas) {
        
        NSMutableSet *oldSet = [NSMutableSet set];
        for (HJGroupMemberModel *model in self.allUserList) {
            [oldSet addObject:model.identifier];
        }
        
        NSMutableSet *set = [NSMutableSet set];
        for (HJGroupMemberModel *model in datas) {
            [set addObject:model.identifier];
        }
        
        if ([oldSet isEqualToSet:set]) {
            TJLog(@"群成员信息未发生改变不再次刷新");
            return;
        }
        TJLog(@"群成员发生改变信息");
        [self handleDataComplete:datas complete:^{
            [self buildData];
            [self.tableView reloadData];
        }];
    }];
}

- (void)queryGroupMemberDataComplete:( void (^ _Nullable)(void))complete {
    [HJIM.shareIM.groupManager queryGroupMemberListWithGroupId:self.groupModel.groupId completion:^(NSArray<HJGroupMemberModel *> * _Nullable datas) {
        [self handleDataComplete:datas complete:complete];
    }];
}

- (void)loadGroupInfo {
    if (self.groupModel.role.intValue == 1 || self.groupModel.role.intValue == 2) {
        [HJIM.shareIM.groupManager loadGroupInfoByGroupId:self.groupModel.groupId completion:^(HJChatGroupModel * _Nullable groupModel) {
            if (!groupModel) return;
            groupModel.extension = self.groupModel.extension;
            self.groupModel = groupModel;
        }];
    }
}

- (CGFloat)getNoticeHeight {
    CGSize noticeSize = [self.groupModel.notice getStringSizeWithWidth:KScreenWidth - leftRightMargin * 2 font:UIFontMake(12)];
    CGFloat singeLineH = UIFontMake(12).lineHeight;
    NSInteger line = noticeSize.height / singeLineH;
    line = MIN(line, 3);
    return 70 + singeLineH * (line - 1);
}

- (CGFloat)getIntroduceHeightWithModel:(HJCellModel *)cellModel {
    if (self.groupModel.role.intValue == 1 || self.groupModel.role.intValue == 2) {
        return 80;
    } else {
        CGSize introSize = [cellModel.detailText getStringSizeWithWidth:KScreenWidth - 100 font:UIFontMake(13)];
        return 52 + introSize.height;
    }
}

- (void)handleDataComplete:(NSArray<HJGroupMemberModel *> * _Nullable)datas complete:( void (^ _Nullable)(void))complete {
     
    
    NSArray *sortedModels = [HJIM.shareIM.groupManager groupMemberModelsSort:datas];
    self.allUserList = sortedModels;
    
    HJGroupMemberModel *addModel = [HJGroupMemberModel addModel];
    HJGroupMemberModel *removeModel = [HJGroupMemberModel removeModel];
    
    NSMutableArray *administratorList = [NSMutableArray array];
    NSMutableArray *userList = [NSMutableArray array];
    NSMutableArray *userSortedModels = [NSMutableArray array];
    NSMutableArray *operateModels = [NSMutableArray array];
    
    NSInteger maxAdministratorCount = 8;
    NSInteger maxMemberCount = 500;
    NSInteger maxShowCount = 10;

    if (self.groupModel.managerLimit) {
        maxAdministratorCount = self.groupModel.managerLimit.intValue;
    }
    
    if (self.groupModel.maxMemberNums) {
        maxMemberCount = self.groupModel.maxMemberNums.intValue;
    }
        
    HJGroupMemberModel *ownerModel = nil;
    //管理员的
    for (HJGroupMemberModel *obj in sortedModels) {
        
        if ([obj.userId isEqualToString:HJUserInfo.userId]) {
            self.groupModel.role = @(obj.role);
        }
        
        if (obj.role == 1) {
            ownerModel = obj;
        } else if (obj.role == 2) {
            if (administratorList.count <= maxAdministratorCount) {
                [administratorList addObject:obj];
            }
        } else if (obj.role == 3) {
            [userSortedModels addObject:obj];
        }
    }
     
    
    [operateModels removeAllObjects];
    
    //只有群组有权限添加管理员和群转让
    NSInteger role = self.groupModel.role.intValue;
    
    if (role == 1) {
        if (administratorList.count < maxAdministratorCount) {
            [operateModels addObject:addModel];
        }
        if (administratorList.count > 1) {
            [operateModels addObject:removeModel];
        }
    }
    
    [administratorList addObjectsFromArray:operateModels];
    
    if (ownerModel) {
        [administratorList insertObject:ownerModel atIndex:0];
    }
    
    //群成员
    //如果大于设置的最大的群成员个数, 是没有加号的
    [operateModels removeAllObjects];
    
    if (role == 1 || role == 2 || role == 3) {
        if (sortedModels.count < maxMemberCount) {
            [operateModels addObject:addModel];
        }
    }
    
    if (role == 1 || role == 2) {
        //如果群成员个数只有群主是没有减号的
        HJGroupMemberModel *memberModel = sortedModels.firstObject;
        if (!(sortedModels.count == 1 && memberModel.role == 1)) {
            [operateModels addObject:removeModel];
        }
    }
    
    if (userSortedModels.count <= maxShowCount - operateModels.count) {//截取
        [userList addObjectsFromArray:userSortedModels];
    } else {//截取
       NSArray *subarray = [userSortedModels subarrayWithRange:NSMakeRange(0, maxShowCount - operateModels.count)];
       [userList addObjectsFromArray:subarray];
    }
    
    [userList addObjectsFromArray:operateModels];
    
    self.groupModel.administratorList = administratorList;
    self.groupModel.userList = userList;
    self.groupModel.memberNums = @(sortedModels.count);
    [self.groupModel bg_saveOrUpdate];
    
    dispatch_async_main_queue(^{
        if (complete) {
            complete();
        }
    });

}

- (HJCellModel *)buildModelWithKey:(NSString *)key {
    HJCellModel *model = [self.modelDict objectForKey:key];
    if (!model) {
        model = [[HJCellModel alloc] init];
        model.identifier = key;
        [self.modelDict setObject:model forKey:key];
    }
    
    if ([key isEqualToString:@"introduction"]) {
        model.anyObject = self.groupModel;
        NSString *content = self.groupModel.intro;
        if (isEmptyString(content)) {
            content = groupDefaultIntroduce;
        }
        model.detailText = [NSString stringWithFormat:@"Introduction: %@", content];
        model.height = [self getIntroduceHeightWithModel:model];
        return model;
    }
    
    if ([key isEqualToString:@"administrators"]) {
        model.text = @"Administrators";
        model.anyObject = self.groupModel.administratorList;
        model.textFieldValue = toString(self.groupModel.role);
        NSInteger row = 1 + (self.groupModel.administratorList.count - 1) / 5;
        model.height = row * 85 + 35 + 10;
        return model;
    }
    
    if ([key isEqualToString:@"members"]) {
        model.text = [NSString stringWithFormat:@"Group Members (%@)", self.groupModel.memberNums];
        model.anyObject = self.groupModel.userList;
        model.textFieldValue = toString(self.groupModel.role);
        NSInteger row = self.groupModel.userList.count > 5 ? 2 : 1;
        model.height = row * 85 + 35 + 10;
        return model;
    }
    
    if ([key isEqualToString:@"notice"]) {
        model.height = [self getNoticeHeight];
        model.text = @"Group notice";
        model.anyObject = self.groupModel;
        return model;
    }
    
    if ([key isEqualToString:@"mute"]) {
        model.text = @"Mute";
        model.isOn = self.groupModel.isMute.boolValue;
        model.separatorInset = UIEdgeInsetsMake(0, leftRightMargin, 0, leftRightMargin);
        return model;
    }
    
    if ([key isEqualToString:@"top"]) {
        model.text = @"Top";
        model.isOn = self.groupModel.isTop.boolValue;
        model.showLine = NO;
        return model;
    }
    
    return nil;
}

- (NSIndexPath *)indexPathWithKey:(NSString *)key {
     __block NSIndexPath *indexPath = nil;
    [self.datas enumerateObjectsUsingBlock:^(NSArray<HJCellModel *> * _Nonnull array, NSUInteger idx, BOOL * _Nonnull stop) {
        [array enumerateObjectsUsingBlock:^(HJCellModel * _Nonnull cellModel, NSUInteger idx1, BOOL * _Nonnull stop1) {
            if ([key isEqualToString:cellModel.identifier]) {
                indexPath = [NSIndexPath indexPathForRow:idx1 inSection:idx];
            }
        }];
    }];
    return indexPath;
}

- (void)reloadCellWithKey:(NSString *)key {
    NSIndexPath *indexPath = [self indexPathWithKey:key];
    if (indexPath) {
        [UIView setAnimationsEnabled:NO];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        [UIView setAnimationsEnabled:YES];
    } else {
        [self.tableView reloadData];
    }
}

- (void)buildData {
    
    [self.datas removeAllObjects];
    [self.modelDict removeAllObjects];
    
    NSInteger role = self.groupModel.role.intValue;
    
    NSArray *commonDatas = @[
        @[
            [self buildModelWithKey:@"introduction"]
        ],
        @[
            [self buildModelWithKey:@"administrators"],
            [self buildModelWithKey:@"members"]
        ],
    ];
    
    NSMutableArray *section3Datas = @[
        [self buildModelWithKey:@"notice"],
    ].mutableCopy;
    
    if (role == 1 || role == 2) {
        [section3Datas insertObject:[HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
            model.identifier = @"groupManager";
            model.text = @"Manage Group";
            model.textFont = UIFontMediumMake(14);
        }] atIndex:1];
    }
    
    
    [self.datas addObjectsFromArray:commonDatas];
    [self.datas addObject:section3Datas];
    
    if (role == 1 || role == 2 || role == 3) {
        [self.datas addObject:@[
            [self buildModelWithKey:@"mute"],
            [self buildModelWithKey:@"top"]
        ]];
    }

    if (role == 1) {
        if (_isShareOpen) {
            [self.datas addObject:@[
                [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.identifier = @"sendMessage";
                model.text = @"Send message";
                model.showLine = NO;
                model.textColor = UIColor.tj_333333Color;
            }]]];
        }
        [self.datas addObject:@[
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
            model.identifier = @"founder";
            model.text = @"Select new founder";
            model.showLine = NO;
        }]]];
        [self.datas addObject:@[
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
            model.identifier = @"disband";
            model.text = @"Disband group";
            model.textColor = UIColor.tj_FF5100Color;
            model.showLine = NO;
        }]]];
    } else if (role == 2 || role == 3) {
        
        if (_isShareOpen) {
            [self.datas addObject:@[
                [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.identifier = @"sendMessage";
                model.text = @"Send message";
                model.showLine = NO;
                model.textColor = UIColor.tj_333333Color;
            }]]];
        }
        
        [self.datas addObject:@[
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
            model.identifier = @"leave";
            model.text = @"Leave Group";
            model.showLine = NO;
            model.textColor = UIColor.tj_FF5100Color;
        }]]];

    } else {
        
        if (self.isShareOpen) {
            if (self.groupModel.userStatus == 3) {
                [self.datas addObject:@[
                    [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                    model.identifier = @"pending";
                    model.text = @"Pending review";
                    model.showLine = NO;
                    model.textColor = UIColor.tj_BEBDCAColor;
                }]]];
            } else {
                [self.datas addObject:@[
                    [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                    model.identifier = @"join";
                    model.text = @"Join Group";
                    model.showLine = NO;
                    model.textColor = UIColor.tj_333333Color;
                }]]];
            }
        }
    }
    
    [self.datas enumerateObjectsUsingBlock:^(NSArray<HJCellModel *> * _Nonnull array, NSUInteger idx, BOOL * _Nonnull stop) {
        for (HJCellModel *cellModel in array) {
            [self.modelDict setObject:cellModel forKey:cellModel.identifier];
        }
    }];
}
 
- (NSMutableDictionary *)modelDict {
    if (!_modelDict) {
        _modelDict = [NSMutableDictionary dictionary];
    }
    return _modelDict;
}


- (NSMutableArray<NSArray<HJCellModel *> *> *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (void)popViewController {
    [super popViewController];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self loadGroupInfo];
    //如果是群成员需要踢人了不会马上刷新
    if (self.groupModel.role.intValue == 3 || self.groupModel.role.intValue == 0) {
        [self loadGroupMemberData];
    }
}

- (void)dealloc {
    if (self.popBlock) {
        self.popBlock();
    }
    NSLog(@"%s", __func__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

